<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-09-16 14:17:35
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 加料单
 */

namespace App\Http\Services\Finance;


use App\Http\Services\Service;
use App\Repositories\FinanceCloseRepository;
use App\Repositories\FinanceVoucherDetailsRepository;
use App\Repositories\FinanceVoucherRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property FinanceCloseRepository $repository
 */
class CloseService extends Service
    {

    public function boot(FinanceCloseRepository $repository)
        {
        $this->repository = $repository;
        }

    protected function set()
        {
        $status_id = request("status_id");
        $year      = request("year");
        $month     = request("month");
        $opr       = "<";
        if ($status_id === 0) {
            $opr = ">";
            }

        $gdata = $this->repository
            ->where('year', $opr . "=", $year)
            ->where('month', $opr, $month)
            ->where("status_id", "<>", $status_id)
            ->first();

        if ($gdata) {
            fail("必须先" . ($status_id == 0 ? '取消' : '结账') . $gdata['month'] . '月');
            }
        $gdata = $this->repository->where('year', $year)->where('month', $month)->first();
        return auditSave($gdata, $status_id != 0);
        }

    public function list()
        {
        $year  = date("Y");
        $count = $this->repository->where('year', $year)->count();
        if ($count == 0) {
            array_filter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], function ($month) use ($year)
                {
                $this->repository->insert(['month' => $month, 'year' => $year]);
                });
            }
        $data = $this->repository
            ->orderBy('year', 'desc')
            ->orderBy('month', 'desc')
            ->where('year', "<=", $year)
            ->where('month', "<=", date("m"))
            ->limit(12)->get();
        return $data;
        }

    }